<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Cache;

class SystemConfig extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'config_key',
        'config_value',
        'config_type',
        'description',
        'is_public',
        'is_encrypted'
    ];

    protected $casts = [
        'config_value' => 'json',
        'is_public' => 'boolean',
        'is_encrypted' => 'boolean'
    ];

    protected $dates = ['deleted_at'];

    // 配置类型常量
    const TYPE_SYSTEM = 'system';
    const TYPE_PAYMENT = 'payment';
    const TYPE_NOTIFICATION = 'notification';
    const TYPE_SECURITY = 'security';

    // 获取配置值（带缓存）
    public static function getConfig($key, $default = null)
    {
        $cacheKey = 'system_config_' . $key;
        
        return Cache::remember($cacheKey, 3600, function () use ($key, $default) {
            $config = self::where('config_key', $key)->first();
            return $config ? $config->config_value : $default;
        });
    }

    // 设置配置值
    public static function setConfig($key, $value, $type = self::TYPE_SYSTEM, $description = null)
    {
        $config = self::updateOrCreate(
            ['config_key' => $key],
            [
                'config_value' => $value,
                'config_type' => $type,
                'description' => $description
            ]
        );

        // 清除缓存
        Cache::forget('system_config_' . $key);

        return $config;
    }

    // 获取公开配置
    public static function getPublicConfigs()
    {
        return self::where('is_public', true)
            ->pluck('config_value', 'config_key')
            ->toArray();
    }
}